/*
 * Copyright 2014-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.grayson.mykafka.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * KafkaProducer
 *
 * @Description:
 * @Author: grayson
 * @Version 1.0
 * @Date: 2021-10-11 11:27
 **/
@RestController
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @GetMapping("/kafka/{msg}")
    public void sendMessage(@PathVariable("msg") String msg) {
        kafkaTemplate.send("test_topic", msg);
    }

    @GetMapping("/kafka/callback/{msg}")
    public void sendCallBackMessage(@PathVariable("msg") String msg) {
        kafkaTemplate.send("test_topic", msg).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable ex) {
                System.out.println("msg send fail:" + ex.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> result) {
                System.out.println("msg send success:" + result.getRecordMetadata().topic() + "-" +
                        result.getRecordMetadata().partition() + "-" + result.getRecordMetadata().offset());
            }
        });
    }

    public void sendTransactionMessage(){
        //当报错时，消息不会发送出去
        kafkaTemplate.executeInTransaction(operations -> {
            operations.send("test_topic","test transaction");
            throw new RuntimeException("fail");
        });
    }
}
